import axios from 'axios'
import { ENV } from 'common/js/process'

export let API = ENV.API

export const ERR_CODE = 200

/** url 添加时间戳
 * @return {string}
 */
export const API_TIMESTAMP = url => url + '?timestamp=' + Date.now()

/**
 * 取消重复请求
 */
const pendingRequest = new Map()

export function generateReqKey (config) {
  const { method, url, params, data } = config
  return [method, url, JSON.stringify(params), JSON.stringify(data)].join('&')
}

export function addPendingRequest (config) {
  const requestKey = generateReqKey(config)
  config.cancelToken = config.cancelToken || new axios.CancelToken((cancel) => {
    if (!pendingRequest.has(requestKey)) {
      pendingRequest.set(requestKey, cancel)
    }
  })
}

export function removePendingRequest (config) {
  const requestKey = generateReqKey(config)
  if (pendingRequest.has(requestKey)) {
    const cancelToken = pendingRequest.get(requestKey)
    cancelToken(requestKey)
    pendingRequest.delete(requestKey)
  }
}
